<template>
  <el-row :gutter="20" style="margin: 10px 10px 0 5px">
    <el-col :span="6"
      ><div class="grid-content bg-purple">
        <CateGory @tree-node-click="treeNodeClick"></CateGory>
      </div>
    </el-col>
    <el-col :span="18"
      ><div class="grid-content bg-purple">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="所属分类" prop="catelogId">
            <el-cascader
              placeholder="请选择所属分类"
              v-model="queryParams.catelogPath"
              :options="categoryList"
              :props="cateprops"
              @keyup.enter.native="handleQuery"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="组名" prop="attrGroupName">
            <el-input
              v-model="queryParams.attrGroupName"
              placeholder="请输入组名"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="描述" prop="descript">
            <el-input
              v-model="queryParams.descript"
              placeholder="请输入描述"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['cloudmallproduct:attrGroup:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['cloudmallproduct:attrGroup:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['cloudmallproduct:attrGroup:remove']"
              >批量删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['cloudmallproduct:attrGroup:export']"
              >导出</el-button
            >
          </el-col>
          <el-col :span="2" style="text-align: right">
            <!-- 切换分类显示方式的按钮 -->
            <el-button type="primary" size="mini" @click="toggleCategoryDisplay">
              {{ showFullPath ? "显示末级分类" : "显示完整路径" }}
            </el-button>
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="attrGroupList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" prop="attrGroupId">
            <template #default="{ $index }">
              {{
                queryParams.pageNum * queryParams.pageSize -
                queryParams.pageSize +
                $index +
                1
              }}
            </template>
          </el-table-column>

          <el-table-column label="组名" align="center" prop="attrGroupName" />
          <el-table-column label="排序" align="center" prop="sort" />
          <el-table-column label="描述" align="center" prop="descript" />
          <el-table-column label="组图标" align="center" prop="icon" />
          <el-table-column label="所属分类" align="center" prop="catelogId">
            <template #default="row">
              <!-- 注意：这里的变量名是 row，直接对应行数据 -->
            {{ 
                showFullPath 
                  ? getCategoryFullPath(row) 
                  : getCategoryName(row) 
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
               <el-button
                size="mini"
                type="text"
                icon="el-icon-eleme"
                @click="handleRelList(scope.row)"
                v-hasPermi="['cloudmallproduct:attrGroup:list']"
                >关联</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['cloudmallproduct:attrGroup:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['cloudmallproduct:attrGroup:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改属性分组对话框 -->
        <el-dialog
          :title="title"
          :visible.sync="open"
          width="500px"
          append-to-body
        >
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="组名" prop="attrGroupName">
              <el-input v-model="form.attrGroupName" placeholder="请输入组名" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序" />
            </el-form-item>
            <el-form-item label="描述" prop="descript">
              <el-input v-model="form.descript" placeholder="请输入描述" />
            </el-form-item>
            <el-form-item label="组图标" prop="icon">
              <el-input v-model="form.icon" placeholder="请输入组图标" />
            </el-form-item>
            <el-form-item label="所属分类" prop="catelogId">
              <el-cascader
                placeholder="请选择所属分类"
                v-model="form.catelogPath"
                :options="categoryList"
                :props="cateprops"
              ></el-cascader>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </el-col>
  </el-row>
</template>

<script>
import {
  listAttrGroup,
  getAttrGroup,
  delAttrGroup,
  addAttrGroup,
  updateAttrGroup,
} from "@/api/product/attrGroup";
import { listWithTree } from "@/api/product/category";
import CateGory from "@/components/category/index.vue";

export default {
  name: "AttrGroup",
  components: {
    CateGory,
  },
  data() {
    return {
      // 所有分类
      categoryList: [],
      // 分类id对应的完整分类数组
      catelogPath: [],
      // 控制分类显示方式：true显示完整路径，false显示末级名称
      showFullPath: false,
      cateprops: {
        value: "catId",
        label: "name",
        children: "children",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 属性分组表格数据
      attrGroupList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        attrGroupName: null,
        sort: null,
        descript: null,
        icon: null,
        catelogId: null,
        catelogPath: [],
      },
      // 表单参数
      form: {
        // 存储分类的完整路径ID数组
        catelogPath: [],
        attrGroupId: null,
        attrGroupName: null,
        sort: null,
        descript: null,
        icon: null,
        // 单个分类ID，用于提交到后端
        catelogId: null,
      },
      // 表单校验
      rules: {
        attrGroupName: [
          { required: true, message: "请输入组名", trigger: "blur" },
        ],
        catelogPath: [
          { required: true, message: "请选择所属分类", trigger: "change" },
        ],
      },
    };
  },
  created() {
     // 先获取分类树，再获取表格数据
    this.getCateGoryList().then(() => {
    this.getList();
  }).catch(error => {
    console.error("分类树加载失败，仍尝试获取表格数据：", error);
    this.getList();
  });
    
  },
  methods: {
    // 查询分类关联的
    // 切换分类显示方式
    toggleCategoryDisplay() {
      this.showFullPath = !this.showFullPath;
    },

    // 根据分类ID获取末级分类名称
    getCategoryName(data) {
       let catelogId = data.row.catelogId;
      if (!catelogId) return "未知分类";
      const findNode = (tree, id) => {
        for (const node of tree) {
          if (String(node.catId) === String(id)) {
            return node;
          }
          if (node.children && node.children.length > 0) {
            const found = findNode(node.children, id);
            if (found) return found;
          }
        }
        return null;
      };

      const node = findNode(this.categoryList, catelogId);
      return node ? node.name : "未知分类";
    },

    // 根据分类ID获取完整分类路径
    getCategoryFullPath(data) {
      let catelogId = data.row.catelogId;
      if (!catelogId) return "未知分类";

      const path = [];
      const findPath = (tree, id) => {
        for (const node of tree) {
          path.push(node.name);
          if (node.catId === id) {
            return true;
          }
          if (node.children && node.children.length > 0) {
            if (findPath(node.children, id)) {
              return true;
            }
          }
          path.pop();
        }
        return false;
      };

      const found = findPath(this.categoryList, catelogId);
      return found ? path.join("/") : "未知分类";
    },

// 获取所有商品分类，确保返回Promise
getCateGoryList() {
  return new Promise((resolve, reject) => {
    listWithTree().then((response) => {
      let rawData = response.rows || [];
      this.categoryList = this.filterTreeByShowStatus(rawData);
      resolve();
    }).catch(error => {
      console.error("获取分类列表失败：", error);
      this.categoryList = [];
      reject(error);
    });
  });
},
    // 递归过滤树形数据：移除showStatus=0的节点
    filterTreeByShowStatus(tree) {
      return tree
        .filter((node) => node.showStatus === 1) // 只保留showStatus=1的节点
        .map((node) => {
          // 对每个节点的children也进行递归过滤
          if (node.children && node.children.length > 0) {
            node.children = this.filterTreeByShowStatus(node.children);
          }
          return node;
        });
    },
    // 树节点点击
    treeNodeClick(data, node, component) {
      console.log("树节点信息", data);
      this.loading = true;
      listAttrGroup({
        catelogId: data.catId,
      }).then((response) => {
        this.attrGroupList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询属性分组列表 */
    getList() {
      this.loading = true;
      listAttrGroup(this.queryParams).then((response) => {
        this.attrGroupList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        attrGroupId: null,
        attrGroupName: null,
        sort: null,
        descript: null,
        icon: null,
        catelogId: null,
        catelogPath: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (
        this.queryParams.catelogPath &&
        this.queryParams.catelogPath.length > 0
      ) {
        this.queryParams.catelogId =
          this.queryParams.catelogPath[this.queryParams.catelogPath.length - 1];
      } else {
        this.queryParams.catelogId = null; // 空值时，将 catelogId 置为 null（后端通常识别 null 为“不筛选”）
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.catelogPath = [];
      this.queryParams.catelogId = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.attrGroupId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加属性分组";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log("修改", row);
      this.reset();
      const attrGroupId = row.attrGroupId || this.ids;
      getAttrGroup(attrGroupId).then((response) => {
        this.form = response.data;
        // 回显分类路径
        this.setCategoryPath(response.data.catelogId);
        this.open = true;
        this.title = "修改属性分组";
      });
    },

    // 根据分类ID设置分类路径（用于修改时回显）
    setCategoryPath(catelogId) {
      if (!catelogId) return;

      const path = [];
      const findPath = (tree, id) => {
        for (const node of tree) {
          path.push(node.catId);
          if (node.catId === id) {
            return true;
          }
          if (node.children && node.children.length > 0) {
            if (findPath(node.children, id)) {
              return true;
            }
          }
          path.pop();
        }
        return false;
      };

      findPath(this.categoryList, catelogId);
      this.form.catelogPath = path;
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 分类id赋值
          if (this.form.catelogPath && this.form.catelogPath.length > 0) {
            this.form.catelogId =
              this.form.catelogPath[this.form.catelogPath.length - 1];
          } else {
            this.$message.error("请选择所属分类");
            return;
          }

          if (this.form.attrGroupId != null) {
            updateAttrGroup(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttrGroup(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const attrGroupIds = row.attrGroupId || this.ids;
      this.$modal
        .confirm('是否确认删除属性分组编号为"' + attrGroupIds + '"的数据项？')
        .then(function () {
          return delAttrGroup(attrGroupIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "cloudmallproduct/attrGroup/export",
        {
          ...this.queryParams,
        },
        `attrGroup_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
